package org.performancetracker.simple;

import org.performancetracker.api.Aggregator;
import org.performancetracker.api.Reporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Basic TrackerAggregator implementation using slf4j and logback to aggregate.
 *
 * TODO: A logback configuration that logs to a database.
 * TODO: A correct statement to log to DB in conjunction with logback.
 *
 * @author: jaronschut
 */

public class AggregatorImpl implements Aggregator {

    /* The statement logged to slf4j */
    private static final String STATEMENT = "Aggregator[{}] StartTime[{}] ElapsedTime[{}] Message[{}]";

    /* The default aggregator */
    private static final org.performancetracker.simple.AggregatorImpl aggregator = new org.performancetracker.simple.AggregatorImpl(Aggregator.DEFAULT_AGGREGATOR_NAME);

    /* The slf4j logger belonging to this instance */
    private Logger aggregatorLog;

    /* The name of the aggregator and thus of the slf4j log */
    private String aggregatorName;

    /**
     * Get the singleton default aggregator.
     *
     * @return
     */
    protected static org.performancetracker.simple.AggregatorImpl getInstance() {
        return aggregator;
    }

    /**
     * Non public constructor as it wil only be instantiated by the TrackerAggragatorFactoryImpl in the same package.
     *
     * @return
     */
    public AggregatorImpl(String aggregatorName) {
        assert(aggregatorName != null);

        this.aggregatorName = aggregatorName;
        this.aggregatorLog = LoggerFactory.getLogger(this.aggregatorName);
    }

    /**
     * Report the tracked performance.
     * Basic implementation of tracker aggregator uses slf4j and logback as the performance aggregator.
     * Use logback configuration to
     *
     * @param reporter
     */
    public void aggregate(Reporter reporter) {
        aggregatorLog.debug(STATEMENT, new Object[]{
                    this.getAggregatorName(),
                    reporter.getStartTime(),
                    reporter.getElapsedTime(),
                    reporter.getMessage()
        });
    }

    /**
     * Return aggregator name or notify it is the
     *
     * @return
     */
    public String getAggregatorName() {
        return aggregatorName;
    }
}